package com.core.life.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.core.common.dao.Pager;
import com.core.life.dao.IConsumeItemDao;
import com.core.life.dao.IConsumeRecordDao;
import com.core.life.entity.ConsumeItemEntity;
import com.core.life.entity.ConsumeRecordEntity;
import com.core.life.service.IAccountingRelationsService;
import com.core.life.service.IConsumeRecordService;
import com.core.life.service.IImageService;
import com.core.life.vo.ConsumeRecordVo;
import com.core.life.vo.ImageVo;
import com.core.sys.service.IUserService;
import com.core.sys.vo.UserVo;
import com.utils.date.DateUtil;

@Service
public class ConsumeRecordServiceImpl implements IConsumeRecordService{

	@Resource
	private IConsumeRecordDao consumeRecordDao;
	@Resource
	private IConsumeItemDao consumeTypeDao;
	@Resource
	private IImageService imageService;
	@Resource
	private IUserService userService;
	@Resource
	private IAccountingRelationsService accountingRelationsService;
	
	@Transactional
	@Override
	public void save(ConsumeRecordVo vo) throws Exception {
		ConsumeItemEntity consumeItem = consumeTypeDao.get(vo.getConsumeItemId());
		if(null != consumeItem){
			ConsumeRecordEntity entity = new ConsumeRecordEntity();
			entity.setConsumeMoney(vo.getConsumeMoney());
			entity.setConsumeItem(consumeItem);
			entity.setCreateUser(vo.getCreateUser());
			entity.setUpdateUser(entity.getUpdateUser());
			entity.setPayerUserId(vo.getPayerUserId());
			entity.setUpdateDate(entity.getCreateDate());
			Calendar cal = Calendar.getInstance();
			cal.setTime(entity.getCreateDate());
			entity.setYear(cal.get(Calendar.YEAR));
			entity.setMonth(cal.get(Calendar.MONTH) + 1);
			entity.setDay(cal.get(Calendar.DATE));
			entity.setDescription(vo.getDescription());
			
			entity.setConsumeUserIds(this.getSortConsumeUserIds(vo.getConsumeUserIds()));
			
			consumeRecordDao.save(entity);
			accountingRelationsService.saveAccountingRelations(entity, vo.getConsumeUserIds());
			imageService.saveImage(vo.getCheckImgs(), entity);
		}
	}

	//解析排序消费人员
	private String getSortConsumeUserIds(String consumeUserIds){
		String[] userIds = consumeUserIds.split(",");
		String[] consumeUserIdArray = new String[userIds.length];
		for (int i = 0; i < userIds.length; i++) {
			consumeUserIdArray[i] = userIds[i].split("/")[0];
		}
		//升序
		Arrays.sort(consumeUserIdArray);
		return StringUtils.join(consumeUserIdArray, ",");
	}
	
	@Transactional
	@Override
	public void delete(String strIds) {
		if(StringUtils.isNotBlank(strIds)){
			String[] idArray = strIds.split(",");
			List<Long> recordIds = new ArrayList<Long>();
			for (String id : idArray) {
				recordIds.add(Long.parseLong(id));
			}
			accountingRelationsService.deleteAccountingRelationsByConsumeRecordIds(recordIds);;
			imageService.deleteImagesByConsumeRecordIds(recordIds);
			consumeRecordDao.deleteByIds(recordIds);			
		}
	}
	
	@Transactional
	@Override
	public void update(ConsumeRecordVo vo) throws Exception {
		ConsumeItemEntity consumeItem = consumeTypeDao.get(vo.getConsumeItemId());
		if(null != consumeItem){
			ConsumeRecordEntity entity = consumeRecordDao.get(vo.getId());
			entity.setConsumeMoney(vo.getConsumeMoney());
			entity.setConsumeItem(consumeItem);
			entity.setCreateUser(vo.getCreateUser());
			entity.setUpdateUser(entity.getUpdateUser());
			entity.setPayerUserId(vo.getPayerUserId());
			entity.setUpdateDate(entity.getCreateDate());
			entity.setDescription(vo.getDescription());
			
			entity.setConsumeUserIds(this.getSortConsumeUserIds(vo.getConsumeUserIds()));
			
			consumeRecordDao.update(entity);
			accountingRelationsService.updateAccountingRelations(entity, vo.getConsumeUserIds());
			imageService.updateImage(vo.getCheckImgs(), entity);
		}
	}

	@Override
	public Pager<ConsumeRecordVo> getList(int pageIndex, int pageSize, String sort, String order,
			Map<String, Object> optionMap) {
		if(pageIndex == 0){
			pageIndex = 1;
		}
		String strDate = null;
		if(null != optionMap){
			//格式：yyyy-MM
			strDate = (String) optionMap.get("strDate");
		}
		Date countDate = null;
		if(StringUtils.isNotBlank(strDate)){
			//添加月份的第一天，时间格式：yyyy-MM-dd
			strDate = strDate + "-01";
			countDate = DateUtil.format(strDate, "yyyy-MM-dd");
		}else{
			countDate = new Date();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(countDate);
		Map<String, Object> daoOptionMap = new HashMap<String,Object>();
		daoOptionMap.put("year", cal.get(Calendar.YEAR));
		daoOptionMap.put("month", cal.get(Calendar.MONTH) + 1);
		Pager<ConsumeRecordEntity> pager = consumeRecordDao.selectByOption(pageIndex, pageSize, sort, order, daoOptionMap);
		List<ConsumeRecordEntity> entityList = pager.getDatas();
		if(CollectionUtils.isNotEmpty(entityList)){
			List<ConsumeRecordVo> voList = new ArrayList<ConsumeRecordVo>(entityList.size());
			ConsumeRecordVo vo = null;
			UserVo user = null;
			for (ConsumeRecordEntity consumeRecord : entityList) {
				vo = new ConsumeRecordVo();
				vo.setId(consumeRecord.getId());
				vo.setPayerUserId(consumeRecord.getPayerUserId());
				user = userService.getUserByUserId(consumeRecord.getPayerUserId());
				if(null != user)
					vo.setPayerUserName(user.getUserName());
				//vo.setConsumeUserNames(userService.getUserGroupNames(consumeRecord.getConsumeUserIds()));
				vo.setConsumeUserNames(accountingRelationsService.getByConsumeRecordId(consumeRecord.getId()));
				vo.setCreateDate(DateUtil.format(consumeRecord.getCreateDate()));
				vo.setUpdateDate(DateUtil.format(consumeRecord.getUpdateDate()));
				vo.setConsumeMoney(consumeRecord.getConsumeMoney());
				vo.setConsumeItemName(consumeRecord.getConsumeItem().getName());
				vo.setCreateUser(consumeRecord.getCreateUser());
				vo.setUpdateUser(consumeRecord.getUpdateUser());
				vo.setDescription(consumeRecord.getDescription());
				vo.setImages(imageService.getImageListByConsumeRecordId(consumeRecord.getId()));;
				voList.add(vo);
			}
			return new Pager<ConsumeRecordVo>(pageIndex, pageSize, pager.getTotalCount(), voList);
		}
		return null;
	}

	@Override
	public ConsumeRecordVo getById(Long id) {
		ConsumeRecordEntity entity = consumeRecordDao.get(id);
		if(null != entity){
			ConsumeRecordVo vo = new ConsumeRecordVo();
			vo.setId(entity.getId());
			vo.setPayerUserId(entity.getPayerUserId());
			vo.setConsumeMoney(entity.getConsumeMoney());
			vo.setConsumeUserIds(entity.getConsumeUserIds());
			vo.setConsumeItemId(entity.getConsumeItem().getId());
			vo.setDescription(entity.getDescription());
			List<ImageVo> images = imageService.getImageListByConsumeRecordId(entity.getId());
			if(CollectionUtils.isNotEmpty(images))
				vo.setImages(images);;
			return vo;
		}
		return null;
	}

}
